package com.hcc.flow.server.service.sys;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.Hashtable;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.hcc.flow.server.common.utils.StringUtilsV2;

@SuppressWarnings("unused")
@Service
public class QRCodeService  {
	private static final Logger logger = LoggerFactory.getLogger(QRCodeService.class);
	/***
	 * 临时数字二维码
	 */
	public final static String SCENE = "QR_SCENE";
	/***
	 * 临时字符串二维码
	 */
	public final static String STR_SCENE = "QR_STR_SCENE";
	/**
	 * 永久数字二维码
	 */
	public final static String LIMIT_SCENE = "QR_LIMIT_SCENE";
	/***
	 * 永久字符串二维码
	 */
	public final static String LIMIT_STR_SCENE = "QR_LIMIT_STR_SCENE";
	
	@Autowired
	private RedisServer redisServer;
	
	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;

	public static void main(String[] args) {
		
	}

	public void generateCode(HttpServletResponse response,String herfSuffix,String checkCode) throws WriterException, IOException {
		// 这里是URL，扫描之后就跳转到这个界面
		String text = StringUtilsV2.isNotBlank(herfSuffix)?(herfSuffix+"/#/writeoffIndex/menu?checkCode="+checkCode):checkCode;
		logger.debug("扫描后的跳转链接为：{}",text);
		//String text = "http://192.168.4.99/restapi/writeoff/dw/logo?winningLogId=" + winningLogId;
		int width = 400;
		int height = 400;
		// 二维码图片格式
		String format = "png";
		// 设置编码，防止中文乱码
		Hashtable<EncodeHintType, Object> ht = new Hashtable<EncodeHintType, Object>();
		ht.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		// 设置二维码参数(编码内容，编码类型，图片宽度，图片高度,格式)
		BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, ht);
		int b_width = bitMatrix.getWidth();
		int b_height = bitMatrix.getHeight();
		// 建立图像缓冲器
		BufferedImage image = new BufferedImage(b_width, b_height, BufferedImage.TYPE_3BYTE_BGR);
		for (int x = 0; x < b_width; x++) {
			for (int y = 0; y < b_height; y++) {
				image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
			}
		}
		// Set standard HTTP/1.1 no-cache headers.
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		response.setHeader("Pragma", "no-cache");
		// return a jpeg
		response.setContentType(MediaType.IMAGE_PNG_VALUE);
	    // create the text for the image
	    //ByteArrayOutputStream bao = new ByteArrayOutputStream();
	    ServletOutputStream out = response.getOutputStream();
	    // write the data out
	    try {
	    	ImageIO.write(image, format,out);
		    out.flush();  
		    //return bao.toByteArray();
	    } finally{
			out.close();
		}
	}
	
	/**
     * 根据str,font的样式以及输出文件目录
     * @param str	字符串
     * @param font	字体
     * @param outFile	输出文件位置
     * @param width	宽度
     * @param height	高度
     * @throws Exception
     */
    public void createImage(HttpServletResponse response,String str) throws WriterException, IOException {
    	int width = 400;
		int height = 400;
    	Font font = new Font("宋体", Font.BOLD, 30);
        // 创建图片
        //BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR);
    	BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_3BYTE_BGR);
        Graphics g = image.getGraphics();
        g.setClip(0, 0, width, height);
        g.setColor(Color.WHITE);
        // 先用黑色填充整张图片,也就是背景
        g.fillRect(0, 0, width, height);
        // 在换成红色
        g.setColor(Color.RED);
        // 设置画笔字体
        g.setFont(font);
        FontMetrics fontMetrics = g.getFontMetrics(font);
        // 计算出中心点 x 位置
        int centerX = image.getWidth() / 2;
        /** 用于获得垂直居中y */
        if(str.contains("/")){
        	String[] sp = str.split("/");
        	String max = Arrays.stream(sp).max((o1, o2) -> o1.length()>o2.length()?1:o1.length()==o2.length()?0:-1).get();
        	// System.out.println(max+"---->长度:"+max.length());
        	// 文字宽度
        	int textWidth = fontMetrics.stringWidth(max);
        	logger.info("centerX = [" + centerX + "], textWidth = [" + textWidth + "], text = [" + max + "]");
        	int left=centerX - textWidth / 2;
        	int topBegin = 400/sp.length;
        	int c = (sp.length > 2)?1:0;
        	for (int i = 0; i < sp.length; i++) {
				g.drawString(sp[i], left, topBegin+((i+c)*35));
			}
        }else{
        	int textWidth = fontMetrics.stringWidth(str);
        	int left=centerX - textWidth / 2;
        	g.drawString(str, left, 220);
        }
        g.dispose();
        // Set standard HTTP/1.1 no-cache headers.
 		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
 		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
 		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
 		// Set standard HTTP/1.0 no-cache header.
 		response.setHeader("Pragma", "no-cache");
 		// return a jpeg
 		response.setContentType(MediaType.IMAGE_PNG_VALUE);
        ServletOutputStream out = response.getOutputStream();
	    // write the data out
	    try {
	    	ImageIO.write(image, "png",out);
		    out.flush();  
		    //return bao.toByteArray();
	    } finally{
			out.close();
		}
        // 输出png图片
        //ImageIO.write(image, "png", new File("e:/a.png"));
    }
}
